package com.wind.gtest;

import java.util.HashMap;
import java.util.LinkedList;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.wind.gtest.GMapItemManager.GMapGroundManager;
import com.wind.gtest.GMapItemManager.GMapSharpManager;
import com.wind.gtest.bean.SqlDataBean;
import com.wind.gtest.sql.DBManager;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SubActivity extends FragmentActivity implements
		OnCameraChangeListener, OnMarkerClickListener,
		OnInfoWindowClickListener, InfoWindowAdapter, LocationSource,
		LocationListener, OnClickListener {
	private final String TAG = "GTMain";
	// ---------------------------google-----------------------
	private GoogleMap map;
	private GroundOverlay groundOverlaySample;
	private HashMap<Integer, GroundOverlay> overlaysH;
	private LinkedList<GroundOverlay> overLaySimple = new LinkedList<GroundOverlay>();
	private LinkedList<GroundOverlay> overLayDetail = new LinkedList<GroundOverlay>();

	private TextView title;
	private Button btn_add1, btn_add2, btn_clear;

	private static final LatLng SYDNEY = new LatLng(-33.88, 151.21);
	private static final LatLng MOUNTAIN_VIEW = new LatLng(37.4, -122.1);
	final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);

	/**
	 * 当前缩放度
	 */
	float currentZoom = 16;
	Location latestLocation = null;
	OnLocationChangedListener mLocationListener;
	private LocationManager locationManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// ---------------------------google-----------------------
		setContentView(R.layout.activity_sub_main);
		initView();
		// ---------------------------google-----------------------
		// test
		testAvail();
		googleMap();

	}

	private void initView() {
		title = (TextView) findViewById(R.id.title);
		title.setText("林情");

		btn_add1 = (Button) findViewById(R.id.button1);
		btn_add2 = (Button) findViewById(R.id.button2);
		btn_clear = (Button) findViewById(R.id.button3);
		btn_add1.setOnClickListener(this);
		btn_add2.setOnClickListener(this);
		btn_clear.setOnClickListener(this);

	}

	private void googleMap() {

		if (map == null) {
			// normal get
			map = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();
			// mMap = ((MapFragment)
			// getFragmentManager().findFragmentById(R.id.map)).getMap();
		}
		map.setMyLocationEnabled(true);
		map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
		map.setLocationSource(this);
		UiSettings uiSetting = map.getUiSettings();
		// uiSetting.setZoomControlsEnabled(false);
		// uiSetting.setMyLocationButtonEnabled(arg0)
		// 显示缩放大小
		map.setOnCameraChangeListener(this);

		setIconPos();

		// animeMap
		// // Move the camera instantly to Sydney with a zoom of 15.
		// map.moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, 15));
		// // Zoom in, animating the camera.
		// map.animateCamera(CameraUpdateFactory.zoomIn());
		// // Zoom out to zoom level 10, animating with a duration of 2 seconds.
		// map.animateCamera(CameraUpdateFactory.zoomTo(10),2000, null);
		// // Construct a CameraPosition focusing on Mountain View and animate
		// the
		// // camera to that position.
		// CameraPosition cameraPosition = new CameraPosition.Builder()
		// .target(MOUNTAIN_VIEW) // Sets the center of the map to Mountain
		// // View
		// .zoom(17) // Sets the zoom
		// .bearing(90) // Sets the orientation of the camera to east
		// .tilt(30) // Sets the tilt of the camera to 30 degrees
		// .build(); // Creates a CameraPosition from the builder
		// map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

		// MapFragment mMapFragment = MapFragment.newInstance();
		// FragmentTransaction fragmentTransaction = getFragmentManager()
		// .beginTransaction();
		// fragmentTransaction.add(R.id.my_container, mMapFragment);
		// fragmentTransaction.commit();

		// Add markers
		// map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
		// "Hello world"));
		// Marker melbourne = map.addMarker(new MarkerOptions()
		// .position(MELBOURNE)
		// .title("Melbourne")
		// .snippet("Population: 4,137,400")
		// .icon(BitmapDescriptorFactory
		// .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
		// map.setOnMarkerClickListener(this);
		// .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)

		requestLocation();

	}

	private void requestLocation() {
		// TODlocationManager = (LocationManager)
		// getSystemService(LOCATION_SERVICE);

		// You may want to pass a different provider in as the first arg here
		// depending on the location accuracy that you desire
		// see LocationManager.getBestProvider()
		if (locationManager == null) {
			locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		}
		Criteria locationCriteria = new Criteria();
		// locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
		locationManager.requestLocationUpdates(
				locationManager.getBestProvider(locationCriteria, true), 1L,
				// LocationManager.GPS_PROVIDER, 1L,
				2F, this);
		locationManager.requestLocationUpdates(
		// locationManager.getBestProvider(locationCriteria, true), 1L,
				LocationManager.GPS_PROVIDER, 1L, 2F, this);
		// setUpMapIfNeeded();
		// writeBitmap();O Auto-generated method stub

	}

	/**
	 * 设置定位按钮与放大按钮位置
	 */
	private void setIconPos() {
		// Gets the my location button
		View myLocationButton = this.findViewById(R.id.map).findViewById(2);

		// Checks if we found the my location button
		if (myLocationButton != null) {
			// Sets the margin of the button
			ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(
					myLocationButton.getLayoutParams());
			marginParams.setMargins(0, 100, 20, 0);
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					marginParams);
			layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
					RelativeLayout.TRUE);
			myLocationButton.setLayoutParams(layoutParams);
		}

		View zoomControl = this.findViewById(R.id.map).findViewById(1);

		// Checks if we found the my location button
		if (zoomControl != null) {
			// Sets the margin of the button
			ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(
					zoomControl.getLayoutParams());
			marginParams.setMargins(0, 0, 20, 100);
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
					marginParams);
			layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
					RelativeLayout.TRUE);
			layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
					RelativeLayout.TRUE);
			zoomControl.setLayoutParams(layoutParams);
		}

	}

	@Override
	public void onPause() {
		// ---------------------------google-----------------------
		if (locationManager != null) {
			locationManager.removeUpdates(this);
		}
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		// ---------------------------google-----------------------
		// setUpMapIfNeeded();
		if (locationManager != null) {
			requestLocation();
			map.setMyLocationEnabled(true);
		}
	}


	// ---------------------------google-----------------------

	private void writeSampleGround() {
		groundOverlaySample = map.addGroundOverlay(GMapGroundManager
				.getInstance().getGroundOptSample());
		// map.moveCamera(CameraUpdateFactory.newLatLngZoom(lat, currentZoom));
		// groundOverlay.setVisible(false);
	}

	// /**
	// * Sets up the map if it is possible to do so (i.e., the Google Play
	// * services APK is correctly installed) and the map has not already been
	// * instantiated.. This will ensure that we only ever call
	// * {@link #setUpMap()} once when {@link #mMap} is not null.
	// * <p>
	// * If it isn't installed {@link SupportMapFragment} (and
	// * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt
	// * for the user to install/update the Google Play services APK on their
	// * device.
	// * <p>
	// * A user can return to this Activity after following the prompt and
	// * correctly installing/updating/enabling the Google Play services. Since
	// * the Activity may not have been completely destroyed during this process
	// * (it is likely that it would only be stopped or paused),
	// * {@link #onCreate(Bundle)} may not be called again so we should call
	// this
	// * method in {@link #onResume()} to guarantee that it will be called.
	// */
	// private void setUpMapIfNeeded() {
	// // Do a null check to confirm that we have not already instantiated the
	// // map.
	// if (map == null) {
	// // Try to obtain the map from the SupportMapFragment.
	// map = ((SupportMapFragment) getSupportFragmentManager()
	// .findFragmentById(R.id.map)).getMap();
	// // Check if we were successful in obtaining the map.
	//
	// // This is how you register the LocationSource
	// map.setLocationSource(this);
	// map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
	// GoogleMapOptions options = new GoogleMapOptions();
	// options.mapType(GoogleMap.MAP_TYPE_SATELLITE)
	// // .compassEnabled(false)
	// // .rotateGesturesEnabled(true).tiltGesturesEnabled(true);
	// // options.compassEnabled(true)
	// ;
	// if (map != null) {
	// setUpMap();
	// }
	// }
	// }

	private void testAvail() {
		int errorCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this); // ��Ϊ�ҵĴ�����Fragment�������getActivity()��Ҫ����Ĵ�����
														// Activiy�У���this�ͺ�
		if (ConnectionResult.SUCCESS != errorCode) {
			GooglePlayServicesUtil.getErrorDialog(errorCode, this, 0).show();
		}

	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		Toast.makeText(this, arg0.getTitle(), Toast.LENGTH_SHORT).show();
		return false;
	}

	@Override
	public void onInfoWindowClick(Marker arg0) {
		Toast.makeText(this, arg0.getTitle(), Toast.LENGTH_SHORT).show();

	}

	@Override
	public View getInfoContents(Marker arg0) {
		return null;
	}

	@Override
	public View getInfoWindow(Marker arg0) {
		return null;
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		mLocationListener = listener;
	}

	@Override
	public void deactivate() {
		mLocationListener = null;
	}

	@Override
	public void onLocationChanged(Location location) {
		/**
		 * Location[mProvider=network,mTime=1306399187835,mLatitude=24.9692934,
		 * mLongitude
		 * =121.23618125,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false
		 * ,mSpeed=
		 * 0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=true,mAccuracy
		 * =60.0,mExtras=Bundle[mParcelledData.dataSize=148]]
		 */
		// Toast.makeText(this,
		// Utils.getDistance(110.313, 21.705, 85.74, 29.64) + "---",
		// Toast.LENGTH_LONG).show();
		if (mLocationListener != null) {
			// 设置当前最近位置
			latestLocation = location;
			// 设置定位信息
			mLocationListener.onLocationChanged(location);
			Log.d("GTest", "getProvider=" + location.getProvider()
					+ "getLatitude经=" + location.getLatitude()// 经度
					+ "getLongitude纬=" + location.getLongitude() // 纬度
					+ "getAccuracy=" + location.getAccuracy());

			// 暂时取消定位
			// Move the camera to the user's location once it's available!
			// map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
			// location.getLatitude(), location.getLongitude()),
			// currentZoom));

			// 图形
			// GMapSharp.getInstance().addPolyline(map,location);
			// addPolygons(location);
			// addCircle(location);

		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onCameraChange(CameraPosition arg0) {
		currentZoom = arg0.zoom;
		LatLng lat = arg0.target;
		LatLng ori = new LatLng(26.17, 119.27);
		LatLng last = null;
		if (latestLocation != null) {
			// TODO
			// 设置返回定位点
			last = new LatLng(latestLocation.getLatitude(),
					latestLocation.getLongitude());
			// 返回特殊设置点
			// last = ori;
		}

		 if (currentZoom > 18) {
		 map.animateCamera(CameraUpdateFactory.zoomTo(18), 500, null);
		 currentZoom = 18;
		 }
		if (currentZoom < 14) {
			map.animateCamera(CameraUpdateFactory.zoomTo(14), 300, null);
			currentZoom = 14;
		}
		if (currentZoom > 17) {
			showDetailOverlay(lat);
		}
		if (lat.latitude > 26.19 || lat.latitude < 26.15) {
			map.animateCamera(
					CameraUpdateFactory.newLatLng(last != null ? last : ori),
					1000, null);
		}
		if (lat.longitude > 119.29 || lat.longitude < 119.25) {
			map.animateCamera(
					CameraUpdateFactory.newLatLng(last != null ? last : ori),
					1000, null);
		}

	}

	private void showDetailOverlay(LatLng lat) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button1:
			// if (groundOverlaySample == null) {
			// writeSampleGround();
			// }
			openOverlayDialog();
			break;
		case R.id.button2:
			if (groundOverlaySample != null) {
				// 0-1;0是不透明，1.0为完全透明
				float trans = groundOverlaySample.getTransparency();
				Log.d(TAG, "trans=" + trans);
				if (trans < 0.8) {
					trans += 0.1f;
				}
				groundOverlaySample.setTransparency(trans);
			}
			break;
		case R.id.button3:
			// if (groundOverlaySample != null) {
			// groundOverlaySample.setVisible(false);
			// }
			// groundOverlaySample = null;
			if (overLaySimple.size() != 0) {
				while (overLaySimple.size() != 0) {
					overLaySimple.removeFirst().remove();
				}
			}
			// while (overLays.iterator().hasNext()) {
			// GroundOverlay type = (GroundOverlay) overLays.iterator().next();
			// type.remove();
			// }
			break;

		default:
			break;
		}
	}

	private void openOverlayDialog() {
		// 显示对话框
		// OverlayDialog dialog=new OverlayDialog(this, getResources(),map);
		// dialog.show();
		// 批量显示图层
		// if (overLaySimple.size() > 5) {
		// overLaySimple.removeFirst().remove();
		// }
		// overLaySimple.add(map.addGroundOverlay(GMapGroundManager.getInstance()
		// .getGroundOptSample()));
		SqlDataBean bean = DBManager.getInstance().searchBean(1);
		GMapSharpManager.getInstance().addSqlDataBean(map, bean);
		// 图形
		// GMapSharpManager.getInstance().addPolyline(map);
	}
}
